<template>
  <div class="app">
    <!-- 面包屑导航区域 开始 -->
    <el-breadcrumb class="breadcrumb" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>书籍管理</el-breadcrumb-item>
      <el-breadcrumb-item>上架书籍</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航区域 开始 -->
    <!-- 书籍添加 from 表单区域 开始  -->
    <div>
      <el-form
        ref="bookFormRef"
        :rules="rules"
        :model="bookForm"
        label-width="120px"
         v-loading="loading"
      >
        <el-form-item  label="书籍名称" prop="bookName">
          <el-input class="my-el-input" v-model="bookForm.bookName"></el-input>
        </el-form-item>
        <el-form-item label="书籍作者" prop="bookAuthor">
          <el-input class="my-el-input" v-model="bookForm.bookAuthor"></el-input>
        </el-form-item>

        <el-form-item label="书籍上架时间" prop="bookLaunchTime">
          <div class="block">
            <el-date-picker
              v-model="bookForm.bookLaunchTime"
              type="datetime"
              class="my-el-input"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="书籍分类" prop="bookClassification">
          <el-select
            @change="changeClassification"
            v-model="bookForm.bookClassification"
            placeholder="请选择"
          >
            <el-option
              v-for="item in bookClassification"
              :key="item._id"
              :label="item.classificationName"
              :value="item.classificationName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="书籍简介" prop="bookIntroduction">
          <el-input
            type="textarea"
            class="my-el-input"
            :rows="4"
            placeholder="请输入内容"
            v-model="bookForm.bookIntroduction"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="书籍封面">
          <el-upload
            ref="uploadImg"
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-change="changeUpload"
            :file-list="fileList"
            :http-request="uploadImg"
            accept="image/png, image/jpeg,image/jpg"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button class="my-el-button el-icon-plus" type="primary" @click="onSubmit">立即创建</el-button>
          <el-button class="my-el-button-default" @click="resetBookForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 书籍添加 from 表单区域 结束  -->
  </div>
</template>
<script>
import {
  getBookClassification,
  uploadImg,
  uploadImgTrue,
  bookAdd
} from '@/network/bookManager'
export default {
  data() {
    return {
      // 添加书籍表单对象
      bookForm: {
        bookName: '',
        bookLaunchTime: '',
        bookIntroduction: '',
        bookClassification: '',
        bookAuthor: '',
        bookCover: '',
        authorId: '',
        bookCollection: 0,
        bookEndOrSerial: 1,
        bookGeneralSection: 0,
        bookNumberOfHits: 0,
        bookNumberOfWords: 0,
        bookStatus: 1,
        bookToUpdate: '1970-1-1 08-00-00'
      },
      // 书籍分类
      bookClassification: [],
      // 上传书籍表单 验证规则
      rules: {
        bookName: [
          { required: true, message: '请输入书籍名称', trigger: 'blur' }
        ],
        bookLaunchTime: [
          { required: true, message: '请选择书籍上架时间', trigger: 'chang' }
        ],
        bookClassification: [
          { required: true, message: '请选择书籍分类', trigger: 'chang' }
        ],
        bookAuthor: [
          { required: true, message: '请输入书籍作者', trigger: 'blur' }
        ],
        bookCover: [
          { required: true, message: '请输入书籍作者', trigger: 'blur' }
        ],
        bookIntroduction: [
          { required: true, message: '请填写书籍描述', trigger: 'blur' }
        ]
      },
      fileList: [], // 文件集合
      imageUrl: '', // 图片预览 路径
      file: null, // 图片文件
      user: null,
      loading:false// 页面加载动画
    }
  },
  methods: {
    // 上传方法
    onSubmit() {
      this.$refs.bookFormRef.validate(async valid => {
        console.info(valid)
        if (!valid) return // 验证表单合法
        if (this.file == null)
          return this.$message.warning('请选择要上传的图片') // 验证图片合法
          if( this.bookForm.bookCover=='') return this.$message.warning('请先等待图片上传完毕')
          this.loading=true
        this.bookForm.authorId = this.user._id // 取出账户id
        this.bookForm.bookIntroduction = this.bookForm.bookIntroduction.replace(
          /\s*/g,
          ''
        )
        let res = await bookAdd(this.bookForm)
        console.info(res)
        if (res.errcode !== 0 || res.id_list.length < 1)
          return this.$message.error(`上架书籍错误：${res.errmsg}`)
        this.$message.success(`上架书籍成功`)
        this.resetBookForm()
         this.loading=false
      })
    },
    // 当书籍分类被改变时触发
    changeClassification(e) {
      console.info(e)
    },
    // 重置表单
    resetBookForm() {
      this.$refs.bookFormRef.resetFields()
      this.bookForm.bookCover=''
      this.imageUrl = ''
      this.file = null
      this.fileList = [] // 文件集合
    },
    // 自定义上传方法
    async uploadImg() {
      let file = this.file
      const isJPG = new RegExp('^image/.*$').test(file.raw.type)
      if (!isJPG) return
      const imgName =
        `boxContent/${this.bookForm.bookName}/novelimg/` +
        new Date().getTime() +
        file.name
      let res = await uploadImg(imgName)
      // 将返回的地址 处理成代理地址
      let website = res.url.substring(0, res.url.indexOf('com') + 3)
      let trueUrl = res.url.replace(website, '/img')
      // 将数据封装成 formData
      const formData = new FormData()
      formData.append('Signature', res.authorization)
      formData.append('key', imgName)
      formData.append('x-cos-security-token', res.token)
      formData.append('x-cos-meta-fileid', res.cos_file_id)
      formData.append('file', file.raw)
      uploadImgTrue(trueUrl, formData) // 最后一步上传图片
      const imgUrl = `https://7a68-zhuma-mbnti-1302831863.tcb.qcloud.la/${imgName}`
      this.bookForm.bookCover = imgUrl // 将图片路径 存入表单对象中
      console.info(imgUrl)
    },
    // 图片上传成功后的回调
    handleAvatarSuccess() {
      this.$message.success('图片上传完成')
    },
    // 图片上传 前的回调
    beforeAvatarUpload(file) {
      console.log(file)
    },
    //文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    changeUpload(file, fileList) {
      this.$refs.bookFormRef.validate(valid => {
        if (!valid) return

        this.file = file
        const isJPG = new RegExp('^image/.*$').test(file.raw.type)
        const isLt2M = file.raw.size / 1024 / 1024 < 2
        this.fileList = fileList
        if (isJPG && isLt2M) {
          this.imageUrl = URL.createObjectURL(file.raw)
          console.info('this.imageUrl:' + this.imageUrl)
          this.fileList.length > 1 ? this.fileList.splice(0, 1) : ''
          this.oldFileUid = file.uid
        } else {
          this.fileList.length > 1
            ? this.fileList.splice(1, 1)
            : this.fileList.splice(0, 1)
          if (!isJPG) {
            this.$message.error('只能上传图片哦')
          } else if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!')
          }
        }
      })
    }
  },
  // vue 生命周期方法
  async mounted() {
    this.user = JSON.parse(sessionStorage.getItem('user'))
    // 请求书籍分类信息
    let classification = await getBookClassification()
    let classificationArray = classification.data
    for (let str in classificationArray) {
      classificationArray[str] = JSON.parse(classificationArray[str])
    }
    this.bookClassification = classificationArray
  }
}
</script>
<style lang="less" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #FD7C27;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
